﻿using System.Collections;
using UnityEngine;
using Random = UnityEngine.Random;

namespace DL.AudioSystem
{
    [RequireComponent(typeof(AudioSource))]
    public class AudioEmitter : MonoBehaviour
    {
        private AudioSource m_AudioSource;
        private Coroutine m_PlayCoroutine;

        private bool m_Active;

        private void Awake()
        {
            m_AudioSource = gameObject.GetOrAdd<AudioSource>();
        }


        public void Init(SoundData data)
        {
            m_AudioSource.clip = data.clip;
            // m_AudioSource.playOnAwake = false;
            m_AudioSource.loop = data.loop;
            // m_AudioSource.volume = 1f;
            m_AudioSource.outputAudioMixerGroup = data.outputGroup;
        }

        public void Play()
        {
            if (null != m_PlayCoroutine)
            {
                StopCoroutine(m_PlayCoroutine);
            }
            m_AudioSource.Play();
            m_Active = true;
            m_PlayCoroutine = StartCoroutine(WaitForSecondsToEnd());
        }
        
        /// <summary>
        /// 停止方法
        /// 该方法会抛出一个异常，该异常为 本游戏对象已经被回收，但是依旧进行了 ReturnToolPool
        /// throw new InvalidOperationException("Trying to release an object that has already been released to the pool.");
        /// 这种情况出现为 本对象已经完成播放回收，但是Manager尝试回收。并打算再次使用 Get 获取
        /// 使用一个活动标记优化掉这个东西
        /// </summary>
        public void Stop()
        {
            if (null != m_PlayCoroutine)
            {
                StopCoroutine(m_PlayCoroutine);
            }
            m_PlayCoroutine = null;
            m_AudioSource.Stop();
            if (m_Active)
            {
                AudioManager.Inst.ReturnToolPool(this);
            }
        }

        public void WithRedomPitch(float min = -0.05f,float max = 0.05f)
        {
            m_AudioSource.pitch = 1 + Random.Range(min, max);
        }
        
        private IEnumerator WaitForSecondsToEnd()
        {
            yield return new WaitWhile(() => m_AudioSource.isPlaying);
            AudioManager.Inst.ReturnToolPool(this);
            m_PlayCoroutine = null;
            m_Active = false;
        }

  
    }
}